package com.fanco.learn_datastruct_leetcode.juc;
import java.util.concurrent.TimeUnit;
/**
 * @author qiaowang 2021/8/23
 * 描述: Java构建死锁Demo
 * 持有A锁 还想要去获取B锁
 */
class DeadLockResource implements Runnable {
    private Object lockA = "锁A";
    private Object lockB = "锁B";
    DeadLockResource(Object lockA, Object lockB) {
        this.lockA = lockA;
        this.lockB = lockB;
    }
    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see Thread#run()
     */
    @Override
    public void run() {
        synchronized (lockA) {
            System.out.println(Thread.currentThread().getName() + "\t 获取" + lockA.toString());
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "等待获取" + lockB.toString());
            synchronized (lockB) {
                System.out.println(Thread.currentThread().getName() + "\t 获取" + lockB.toString());
            }
        }
    }
}
/**
 * @author Fanco
 */
public class DeadLockDemo {
    public static void main(String[] args) {
        DeadLockResource deadLockResource = new DeadLockResource("锁A", "锁B");
        DeadLockResource deadLockResource2 = new DeadLockResource("锁B", "锁A");
        new Thread(deadLockResource, "线程A").start();
        new Thread(deadLockResource2, "线程B").start();
    }
}
